<?php

class Auth {

    protected $_ci;
    
    /**
     * User info singleton instance
     * @var array 
     */
    protected static $_user_info = null;

    public function __construct()
    {
        $this->_ci = & get_instance();
        
        $this->_ci->load->model('backend/user_m', 'user');

        //auto-login the user if they are remembered
        if (!$this->is_logged_in() && $this->_ci->input->cookie('identity') && $this->_ci->input->cookie('remember_token'))
        {
            $this->_login_remembered_user();
        }
    }

    /**
     * Login with email and password
     * @param string $email
     * @param string $password
     * @return boolean 
     */
    public function login($email, $password, $remember)
    {
        //Get user info
        $query = $this->_ci->db->query("SELECT * FROM users WHERE email = ? AND password = ?", array($email, md5($password)));

        if ($query->num_rows() > 0)
        {
            $user = $query->row_array();

            //Update last login time
            $this->update_last_login((int) $user['id']);
            
            //Remember user
            $remember === true && $this->_remember_user($user['id']);
            
            //Set session
            $this->_ci->session->set_userdata(array(
                'user_id'       =>  $user['id'],
                'user_email'    =>  $user['email'],
                'user_name'    =>  $user['username'],
                'user_display'  =>  $user['display_name']
            ));

            return true;
        }

        return false;
    }
    
    /**
     * Logout
     * @return boolean 
     */
    public function logout()
    {
        //Delete the remember me cookies if they exist        
        if ($this->_ci->input->cookie('identity'))
        {
            $this->_ci->input->set_cookie(array('name' => 'identity'));
        }
        
        if ($this->_ci->input->cookie('remember_code'))
        {
            $this->_ci->input->set_cookie(array('name' => 'remember_token'));
        }

        $this->_ci->session->sess_destroy();
       
        return true;
    }
    
    /**
     * get current logged in user
     */
    public function get_user()
    {
        if (self::$_user_info === null)
        {
            self::$_user_info = ($this->is_logged_in()) ? $this->_ci->user->get_by_id($this->_ci->session->userdata('user_id')) : array();
        }
        
        return self::$_user_info;
    }

    /**
     * Update last login time by user id
     * @param int $user_id
     * @return boolean 
     */
    public function update_last_login($user_id)
    {
        return $this->_ci->user->update(array('last_login' => time()), array('id' => $user_id)) === 1;
    }

    /**
     * Remember user for the next login
     * @param int $user_id
     * @return boolean
     */
    protected function _remember_user($user_id)
    {
        $user_id = (int) $user_id;

        if (!$user_id)
        {
            return false;
        }

        $user = $this->_ci->user->get_by_id($user_id);

        if (empty($user))
        {
            return false;
        }

        $salt = sha1($user['password']);

        if ($this->_ci->user->update(array('remember_code' => $salt), array('id' => $user_id)) > -1)
        {
            $this->_ci->input->set_cookie(array(
                'name' => 'identity',
                'value' => 1000000000 + (int)$user['id'],
                'expire' => 604800,
                'httponly' => true,
            ));

            $this->_ci->input->set_cookie(array(
                'name' => 'remember_token',
                'value' => $salt,
                'expire' => 604800,
                'httponly' => true,
            ));

            return true;
        }

        return false;
    }

    protected function _login_remembered_user()
    {

        $identity = (int) $this->_ci->input->cookie('identity', true);
        $remember_token = $this->_ci->input->cookie('remember_token', true);


        //Check for valid data
        if ($identity < 1000000000 || !$remember_token)
        {
            return false;
        }



        $user = $this->_ci->user->get_by_id($identity - 1000000000);

        if (empty($user) || ($user['remember_token'] != $remember_token))
        {
            return false;
        }

        $this->update_last_login($user['id']);

        //Set session
        $this->_ci->session->set_userdata(array(
            'user_id' => $user['id'],            
        ));

        $this->_remember_user($user['id']);

        return true;
    }

    /**
     * Check user logged in
     * @return type 
     */
    public function is_logged_in()
    {
        return (int) $this->_ci->session->userdata('user_id') > 0;
    }
    
    /**
     * Check is root
     * @return boolean 
     */
    public function is_root()
    {
        $user = $this->get_user();
        
        return $user['role_id'] == 1;
    }
    
    /**
     * Check is admin
     * @return boolean 
     */
    public function is_admin()
    {
        $user = $this->get_user();
        
        if(isset($user['group_id']) && $user['group_id'] == 1){
            return 1;
        }
        
        return 0;
    }

}